package com.anmong.cloud.cloudcommon.config.feign;

import com.anmong.cloud.cloudcommon.exception.ApiInvokeException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.Util;

import feign.codec.ErrorDecoder;
import org.apache.commons.lang3.StringUtils;

/**
 * 此解码器解码针对ApiInvokeException异常做异常信息解码,上游应该抛出ApiInvokeException才能把异常信息传递到下游
 * 否则可能会被统一异常信息覆写掉异常信息
 */
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public ApiInvokeException decode(String s, Response response) {
        if (response.body() == null) {
            throw new ApiInvokeException("返回体为空");
        }
        String bodyStr;
        try {
            bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        }
        catch (Exception e){
            throw new ApiInvokeException("返回体结构不正确:"+e.getMessage());
        }
        String message = null;
        if(StringUtils.isNotEmpty(bodyStr)){
            JsonNode result;
            try {
                //先解析统一格式
                result = new ObjectMapper().readTree(bodyStr);
            }
            catch (Exception e){
                throw new ApiInvokeException("返回体结构不正确:"+e.getMessage());
            }
            if (result != null){
                JsonNode messageNode = result.get("message");
                if (messageNode != null){
                    message = messageNode.toString();
                }
            }
        }
        return new ApiInvokeException("微服务调用上游抛出异常:"+message);
    }
}
